package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.common.util.HttpClient;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.payment.service.WxpayService;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WxpayServiceImpl implements WxpayService {
    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderFeignClient orderFeignClient;


    @SneakyThrows
    @Override
    public Map createNative(String orderId) {
        try{
        OrderInfo orderInfo  = orderFeignClient.getOrderInfo(Long.parseLong(orderId));
        // 保存交易记录
        paymentService.savePaymentInfo(orderInfo, PaymentType.WEIXIN.name());
        Map m = new HashMap();
        //1、设置支付参数
        m.put("appid","wx74862e0dfcf69954");
        m.put("mch_id", "1558950191");
        m.put("nonce_str", WXPayUtil.generateNonceStr());
        m.put("body", orderInfo.getTradeBody());
        m.put("out_trade_no", orderInfo.getOutTradeNo());
        //BigDecimal bigDecimal = new BigDecimal(1);
        m.put("total_fee","1");
        m.put("spbill_create_ip", "127.0.0.1");
       // String notify_payment_url = "http://rz33ic.natappfree.cc/api/payment/weixin/callback/notify";
       // "http://guli.shop/api/order/weixinPay/weixinNotify"
        m.put("notify_url", "http://dzbmw9.natappfree.cc/api/payment/weixin/callback/notify");
        m.put("trade_type", "NATIVE");

        //2、HTTPClient来根据URL访问第三方接口并且传递参数
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        //client设置参数
        client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
        client.setHttps(true);
        client.post();
        //3、返回第三方的数据
        String xml = client.getContent();
        Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
        //4、封装返回结果集

        System.out.println(resultMap.toString());

        Map map = new HashMap<>();
        map.put("out_trade_no", orderInfo.getOutTradeNo());
        map.put("orderId", orderInfo.getId());
        map.put("totalFee", "0.01");
        map.put("return_code", resultMap.get("return_code"));
        map.put("result_code", resultMap.get("result_code"));
        map.put("codeUrl", resultMap.get("code_url"));
        map.put("prepay_id", resultMap.get("prepay_id"));

        //微信支付二维码2小时过期，可采取2小时未支付取消订单
        //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
        return map;
    } catch (Exception e) {
        e.printStackTrace();
        return new HashMap<>();
    }
    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId, String paymentType) {
        try {
            PaymentInfo paymentInfoQuery = paymentService.getWXPaymentInfo(orderId, PaymentType.WEIXIN.name());
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no",paymentInfoQuery.getOutTradeNo());
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 关闭交易
     * @param orderId
     * @return
     */
    @Override
    public Boolean closePay(Long orderId) {
        try {
            PaymentInfo paymentInfoQuery = paymentService.getWXPaymentInfo(orderId,PaymentType.WEIXIN.name());
            //1.封装参数
            Map param = new HashMap();
            param.put("appid","wx74862e0dfcf69954");       //公众账号ID
            param.put("mch_id","1558950191");   //商户编号
            param.put("out_trade_no",paymentInfoQuery.getOutTradeNo()); //商户订单编号
            param.put("nonce_str",WXPayUtil.generateNonceStr());    //随机字符串

            String paramXml = WXPayUtil.generateSignedXml(param,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb");

            //2.执行请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/closeorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //3.获取返回数据
            String content = httpClient.getContent();

            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
